package com.fjwt.gz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.AwardUserTimesBO;
import com.fjwt.gz.db.bo.ReceiptContentBo;
import com.fjwt.gz.db.dto.AwardSettingDTO;
import com.fjwt.gz.db.entity.AssetMonthEntity;
import com.fjwt.gz.db.entity.AssetQuarterEntity;
import com.fjwt.gz.db.entity.AwardAgentEntity;
import com.fjwt.gz.db.entity.AwardCouponEntity;
import com.fjwt.gz.db.entity.AwardGoodsEntity;
import com.fjwt.gz.db.entity.AwardScoreEntity;
import com.fjwt.gz.db.entity.AwardSettingEntity;
import com.fjwt.gz.db.entity.AwardVirtualEntity;
import com.fjwt.gz.db.entity.FansAuthEntity;
import com.fjwt.gz.db.entity.FansAwardEntity;
import com.fjwt.gz.service.mapper.AwardSettingMapper;
import com.fjwt.gz.util.JsonUtils;
import com.fjwt.gz.util.PeriodUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 奖品配置信息表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardSettingService extends ServiceImpl<AwardSettingMapper, AwardSettingEntity> {
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private FansAuthService fansAuthService;
    @Autowired
    private AssetMonthService assetMonthService;
    @Autowired
    private AssetQuarterService assetQuarterService;
    @Autowired
    private AwardAgentService awardAgentService;
    @Autowired
    private AwardCouponService awardCouponService;
    @Autowired
    private AwardGoodsService awardGoodsService;
    @Autowired
    private AwardScoreService awardScoreService;
    @Autowired
    private AwardVirtualService awardVirtualService;
    @Autowired
    private AwardSettingMapper awardSettingMapper;


    /**
     * 奖品配置信息表--参与规则的限制
     **/
    public JSONObject AwardSettingRule(Long fansId, String agentNo, ActivityAwardAndSettingBo activityAwardAndSettingBo) {
        //检查周期性限制
        checkPeriodNum(activityAwardAndSettingBo);
        //检查用户实名和资产等级限制
        checkUserAsset(activityAwardAndSettingBo.getIsLimitUser(), activityAwardAndSettingBo.getLimitUserContent(), fansId, agentNo);
        // 检查卡券同一用户周期性发放限制
        return checkEveryonePeriodNum(activityAwardAndSettingBo, fansId);
    }

    public void updateAwardLimitCache(JSONObject awardCheckJson, Long redisOutTime) {
        //更新Redis中参与的次数
        AwardUserTimesBO awardUserTimesBO = awardCheckJson.getObject("awardUserTimesBO", AwardUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(awardUserTimesBO)){
            String awardCurrentTimesKey = awardCheckJson.getString("awardCurrentTimesKey");
            if (ObjectUtils.isEmpty(redisOutTime)) {
                log.info("更新个人参与次数的Redis数据,redisKey:{},redisValue:{}", awardCurrentTimesKey, JSONUtil.toJsonStr(awardUserTimesBO));
                RedisUtil.set(awardCurrentTimesKey, awardUserTimesBO);
            }else {
                log.info("更新个人参与次数的Redis数据,redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", awardCurrentTimesKey, JSONUtil.toJsonStr(awardUserTimesBO), redisOutTime, "TimeUnit.MILLISECONDS");
                RedisUtil.set(awardCurrentTimesKey, awardUserTimesBO, redisOutTime, TimeUnit.MILLISECONDS);
            }
        }
    }

    /**获取奖品的列表以及奖品的配置条件，通过此方法查询出来后在调用AwardSettingRule方法校验每一个奖品配置，然后在上一层进行组装真正通过校验的奖品进行发放**/
    public List<ActivityAwardAndSettingBo> getActivityAwardList(Long activityId, Long redisOutTime) {
        String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.AWARD);
        log.info("活动奖品列表redisKey:{}", activityAwardKey);
        List<ActivityAwardAndSettingBo> awardAndSetting = RedisUtil.getObject(activityAwardKey, new com.alibaba.fastjson2.TypeReference<List<ActivityAwardAndSettingBo>>() {
        });
        if (awardAndSetting == null) {

            awardAndSetting = activityAwardService.getAwardAndSetting(activityId);
            if (awardAndSetting != null && !awardAndSetting.isEmpty()) {
                RedisUtil.set(activityAwardKey, awardAndSetting, redisOutTime, TimeUnit.MILLISECONDS);
                log.info("活动奖品列表，从数据库加载到redis缓存中，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(awardAndSetting), redisOutTime, "TimeUnit.MILLISECONDS");
            }
        } else {
            log.info("活动奖品列表，redis缓存，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(awardAndSetting), redisOutTime, "TimeUnit.MILLISECONDS");
        }
        if (awardAndSetting == null || awardAndSetting.isEmpty()) {
            throw new BizException("活动奖品配置信息有误");
        }
        return awardAndSetting;
    }


    /**
     * 检查卡券总数量周期性发放限制,true超过数量限制，false没有超过
     */
    public void checkPeriodNum(ActivityAwardAndSettingBo activityAwardAndSettingBo) {
        String type = "";
        boolean isOverNum = false;//是否超发
//                判断周期性次数
        final Integer periodType = activityAwardAndSettingBo.getPeriodType();//限制周期类型
        if (periodType != null && periodType > 0) {
            int currentPeriodNum = activityAwardAndSettingBo.getCurrentPeriodTimes();//当前周期次数
            int historyPeriod = activityAwardAndSettingBo.getCurrentPeriodType();//当前类型  第几天 第几周
            final int periodTimes = activityAwardAndSettingBo.getPeriodTimes();//限制周期次数
            int currentPeriod = PeriodUtil.getPeriod(periodType);
            if (currentPeriod == historyPeriod) {
                if (currentPeriodNum >= periodTimes) {
                    type = periodType == 1 ? "日" : periodType == 2 ? "周" : "月";
                    log.info(String.format("该卡券奖品\"%s\"每%s领取数量已达上限", activityAwardAndSettingBo.getAwardName(), type));
                    isOverNum = true;
                } else {
                    currentPeriodNum++;
                    activityAwardAndSettingBo.setCurrentPeriodTimes(currentPeriodNum);
                    isOverNum = false;
                }
            } else {
                activityAwardAndSettingBo.setCurrentPeriodTimes(1);
                activityAwardAndSettingBo.setCurrentPeriodType(currentPeriod);
                isOverNum = false;
            }
        } else {
            return;
        }
        if (isOverNum) {
            throw new BizException(String.format("\"%s\"每%s领取数量已达上限", activityAwardAndSettingBo.getAwardName(), type));
        }else {
            AwardSettingEntity awardSettingEntity = new AwardSettingEntity();
            if (ObjectUtils.isNotEmpty(activityAwardAndSettingBo)) {
            awardSettingEntity.setAwardSettingId(activityAwardAndSettingBo.getAwardSettingId());
            awardSettingEntity.setCurrentPeriodTimes(activityAwardAndSettingBo.getCurrentPeriodTimes());
            awardSettingEntity.setCurrentPeriodType(activityAwardAndSettingBo.getCurrentPeriodType());
            int isUpdate = awardSettingMapper.updateById(awardSettingEntity);
            log.info("更新t_award_setting表，返回结果：{}",isUpdate);
            if (isUpdate == 0) {
                log.info("发放卡券，周期性限制并发问题");
                throw new BizException("活动太火爆了，请稍后再试!");
            }
          }
        }
    }

    /**
     * 检查奖品同一用户总限制和周期性发放限制
     */
    public JSONObject checkEveryonePeriodNum(ActivityAwardAndSettingBo activityAwardAndSettingBo, Long fansId) {
        JSONObject jsonObject = new JSONObject();

        // 用户卡券次数redis缓存key
        String awardCurrentTimesKey = String.format("%s:%s:%s:%s%s", Constants.REDIS_ACTIVITY.AWARD, activityAwardAndSettingBo.getAwardType(), activityAwardAndSettingBo.getAwardId(), Constants.REDIS_ACTIVITY.USER_FILENAME, fansId);
        log.info("奖品每人参与的总次数redisKey:{}", awardCurrentTimesKey);
        // 用户卡券次数redis缓存
        AwardUserTimesBO awardUserTimesBO = RedisUtil.getObject(awardCurrentTimesKey, AwardUserTimesBO.class);
        log.info("奖品每人参与的总次数redisValue:{}", JSONUtil.toJsonStr(awardUserTimesBO));

        // 校验总限制
        final int everyoneMaxNum = activityAwardAndSettingBo.getEveryoneMaxNum();
        if (everyoneMaxNum > 0) {
            if (awardUserTimesBO != null) {
                int totalJoinTimes = awardUserTimesBO.getTotalJoinTimes();
                if (totalJoinTimes >= everyoneMaxNum) {
                    throw new BizException("对不起，您参与的总次数已用完");
                } else {
                    totalJoinTimes++;
                    awardUserTimesBO.setTotalJoinTimes(totalJoinTimes);
                }
            } else {
                awardUserTimesBO = new AwardUserTimesBO();
                awardUserTimesBO.setTotalJoinTimes(1);
            }
        }

        // 校验周期性发放限制
        if (activityAwardAndSettingBo.getEveryonePeriodType() > 0) {
            int currentPeriod = PeriodUtil.getPeriod(activityAwardAndSettingBo.getEveryonePeriodType());
            if (awardUserTimesBO != null) {
                int currentPeriodTimes = awardUserTimesBO.getCurrentPeriodTimes();
                int historyPeriod = awardUserTimesBO.getCurrentPeriod();
                final int periodTimes = activityAwardAndSettingBo.getEveryonePeriodTimes();
                if (currentPeriod == historyPeriod) {
                    if (currentPeriodTimes >= periodTimes) {
                        String type = activityAwardAndSettingBo.getEveryonePeriodType() == Constants.PERIOD.DAY ? "日" : activityAwardAndSettingBo.getEveryonePeriodType() == Constants.PERIOD.WEEK ? "周" : activityAwardAndSettingBo.getEveryonePeriodType() == Constants.PERIOD.MONTH ? "月" : "年";
                        throw new BizException(String.format("对不起，您每%s参与的次数已用完", type));
                    } else {
                        currentPeriodTimes++;
                        awardUserTimesBO.setCurrentPeriodTimes(currentPeriodTimes);
                    }
                } else {
                    awardUserTimesBO.setCurrentPeriodTimes(1);
                    awardUserTimesBO.setCurrentPeriod(currentPeriod);
                }
            } else {
                awardUserTimesBO = new AwardUserTimesBO();
                awardUserTimesBO.setCurrentPeriodTimes(1);
                awardUserTimesBO.setCurrentPeriod(currentPeriod);
            }
        }
        jsonObject.put("awardCurrentTimesKey", awardCurrentTimesKey);
        jsonObject.put("awardUserTimesBO", awardUserTimesBO);
        return jsonObject;
    }

    /**
     * 检查用户资产等级或者是否实名认证校验
     **/
    public void checkUserAsset(int coupon, String content, Long fansId, String agentNo) {
        if (coupon == 1) {
            //查询用户的实名认证信息
            LambdaQueryWrapper<FansAuthEntity> gw = FansAuthEntity.gw();
            gw.eq(FansAuthEntity::getFansId, fansId);
            gw.eq(FansAuthEntity::getAgentNo, agentNo);
            FansAuthEntity fansAuthEntity = fansAuthService.getOne(gw);
            if (ObjectUtils.isEmpty(fansAuthEntity)) {
                throw new BizException("该活动请先实名认证");
            }
        } else if (coupon == 2) {
            //查询用户的资产等级信息

            int lastMonth = DateUtil.lastMonth().monthBaseOne();
            int year = 0;
            if (lastMonth == 12) {
                year = DateUtil.thisYear() - 1;
            } else {
                year = DateUtil.thisYear();
            }
            log.info("用户资产等级查询的年月:{}，{}", year, lastMonth);
            LambdaQueryWrapper<AssetMonthEntity> gw = AssetMonthEntity.gw();
            gw.eq(AssetMonthEntity::getFansId, fansId);
            gw.eq(AssetMonthEntity::getAgentNo, agentNo);
            gw.eq(AssetMonthEntity::getYear, year);
            gw.eq(AssetMonthEntity::getMonth, lastMonth);
            AssetMonthEntity assetMonthEntity = assetMonthService.getOne(gw);
            if (JSONUtil.isNull(assetMonthEntity)) {
                throw new BizException("您当前不符合领取资格");
            }
            int mycontent = assetMonthEntity.getLevel();
            String[] userArray = content.split(",");
            List<String> userList = Arrays.asList(userArray);
            int index = 0;
            for (String user : userList) {
                if (user.equals(String.valueOf(mycontent))) {
                    index++;
                }
            }
            if (index == 0) {
                throw new BizException("您当前不符合领取资格");
            }
        } else if (coupon == 3) {

            LocalDate currentDate = LocalDate.now();
            int year = currentDate.getYear();
            int quarter = (currentDate.getMonthValue() - 1) / 3 + 1;
            int previousQuarter = quarter - 1;
            int previousYear = year;
            if (previousQuarter == 0) {
                previousQuarter = 4;
                previousYear = year - 1;
            }
            log.info("用户资产等级查询的年季:{}，{}", previousYear, previousQuarter);
            LambdaQueryWrapper<AssetQuarterEntity> gw = AssetQuarterEntity.gw();
            gw.eq(AssetQuarterEntity::getFansId, fansId);
            gw.eq(AssetQuarterEntity::getAgentNo, agentNo);
            gw.eq(AssetQuarterEntity::getYear, previousYear);
            gw.eq(AssetQuarterEntity::getQuarter, previousQuarter);
            AssetQuarterEntity assetQuarterEntity = assetQuarterService.getOne(gw);
            if (JSONUtil.isNull(assetQuarterEntity)) {
                throw new BizException("您当前不符合领取资格");
            }
            int mycontent = assetQuarterEntity.getLevel();
            String[] userArray = content.split(",");
            List<String> userList = Arrays.asList(userArray);
            int index = 0;
            for (String user : userList) {
                if (user.equals(String.valueOf(mycontent))) {
                    index++;
                }
            }
            if (index == 0) {
                throw new BizException("您当前不符合领取资格");
            }
        }
    }


    /**
     * 校验是否回执
     **/
    public void checkIsRecipt(ActivityAwardAndSettingBo activityAwardAndSettingBo, String extJson, FansAwardEntity fansAwardEntity) {
        log.info("校验是否回执信息是：activityAwardAndSettingBo：{}，extJson：{}，fansAwardEntity：{}，type：{}", JsonUtils.toJson(activityAwardAndSettingBo), extJson, JsonUtils.toJson(fansAwardEntity), activityAwardAndSettingBo.getAwardType());
        // 奖品配置回执信息
        ReceiptContentBo receiptContentBo = new ReceiptContentBo();
        // 用户奖品额外参数信息
        JSONObject extJsonObject = new JSONObject();
        // 用户传递回执信息
        JSONObject receiptContent = new JSONObject();
        Integer awardType = activityAwardAndSettingBo.getAwardType();
        if (0 == awardType) {
            // 卡券判断是否需要回执参数
            if (1 != activityAwardAndSettingBo.getIsOpenReceipt()) {
                return;
            }
            if (ObjectUtils.isEmpty(activityAwardAndSettingBo.getReceiptContent())) {
                throw new BizException("卡券回执参数配置异常");
            }
            if (ObjectUtils.isEmpty(activityAwardAndSettingBo.getReceiptType())) {
                throw new BizException("卡券回执类型配置异常");
            }
            extJsonObject = JSONObject.parseObject(extJson);
            if (ObjectUtils.isEmpty(extJsonObject) || ObjectUtils.isEmpty(extJsonObject.getString("receiptContent"))) {
                throw new BizException("请填写回执参数");
            }
            receiptContent = JSONObject.parseObject(extJsonObject.getString("receiptContent"));
            receiptContentBo = JSONUtil.toBean(activityAwardAndSettingBo.getReceiptContent(), ReceiptContentBo.class);
        } else if (1 == awardType) {
            // 实物判断是否需要回执参数
            if (1 != activityAwardAndSettingBo.getIsOpenReceipt()) {
                return;
            }
            if (ObjectUtils.isEmpty(activityAwardAndSettingBo.getReceiptContent())) {
                throw new BizException("实物奖品回执参数配置异常");
            }
            if (ObjectUtils.isEmpty(activityAwardAndSettingBo.getReceiptType())) {
                throw new BizException("实物奖品回执类型配置异常");
            }
            extJsonObject = JSONObject.parseObject(extJson);
            if (ObjectUtils.isEmpty(extJsonObject.getString("receiptContent"))) {
                throw new BizException("请填写实物奖品回执参数");
            }
            receiptContent = JSONObject.parseObject(extJsonObject.getString("receiptContent"));
            receiptContentBo = JSONUtil.toBean(activityAwardAndSettingBo.getReceiptContent(), ReceiptContentBo.class);
        }

        if (ObjectUtils.isNotEmpty(receiptContentBo.getName()) && receiptContentBo.getName().isMust() && ObjectUtils.isEmpty(receiptContent.get("name"))) {
            throw new BizException("回执参数{姓名}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getPhone()) && receiptContentBo.getPhone().isMust() && ObjectUtils.isEmpty(receiptContent.get("phone"))) {
            throw new BizException("回执参数{手机号}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getIdCard()) && receiptContentBo.getIdCard().isMust() && ObjectUtils.isEmpty(receiptContent.get("idCard"))) {
            throw new BizException("回执参数{身份证号}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getBankCard()) && receiptContentBo.getBankCard().isMust() && ObjectUtils.isEmpty(receiptContent.get("bankCard"))) {
            throw new BizException("回执参数{银行卡号}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getBankImg()) && receiptContentBo.getBankImg().isMust() && ObjectUtils.isEmpty(receiptContent.get("bankImg"))) {
            throw new BizException("回执参数{银行卡照片}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getAddress()) && receiptContentBo.getAddress().isMust() && ObjectUtils.isEmpty(receiptContent.get("address"))) {
            throw new BizException("回执参数{地址}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getOpenDate()) && receiptContentBo.getOpenDate().isMust() && ObjectUtils.isEmpty(receiptContent.get("openDate"))) {
            throw new BizException("回执参数{开卡日期}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getDepositDate()) && receiptContentBo.getDepositDate().isMust() && ObjectUtils.isEmpty(receiptContent.get("depositDate"))) {
            throw new BizException("回执参数{提额日期}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getDeposit()) && receiptContentBo.getDeposit().isMust() && ObjectUtils.isEmpty(receiptContent.get("deposit"))) {
            throw new BizException("回执参数{额度}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getPension()) && receiptContentBo.getPension().isMust() && ObjectUtils.isEmpty(receiptContent.get("pension"))) {
            throw new BizException("回执参数{养老金账户号}不能为空");
        }
        if (ObjectUtils.isNotEmpty(receiptContentBo.getMchNo()) && receiptContentBo.getMchNo().isMust() && ObjectUtils.isEmpty(receiptContent.get("mchNo"))) {
            throw new BizException("回执参数{商户号}不能为空");
        }
        if ("ACTE028".equals(extJsonObject.getString("templateNo"))) {
            // 检验ACTE028回执信息
            if (ObjectUtils.isEmpty(receiptContentBo.getDeposit().getRemark())) {
                throw new BizException("卡券提升金额区间配置异常");
            }
            JSONObject remark = JSONObject.parseObject(receiptContentBo.getDeposit().getRemark());
            if (ObjectUtils.isEmpty(remark)) {
                throw new BizException("卡券提升金额区间配置异常");
            }
            if (receiptContent.getBigDecimal("deposit").compareTo(remark.getBigDecimal("min")) < 0 || receiptContent.getBigDecimal("deposit").compareTo(remark.getBigDecimal("max")) > 0) {
                throw new BizException("商户资产提升金额不再该卡券区间内，请激活正确区间的卡券");
            }
        }
        // 添加回执参数
        String extraJsonStr = fansAwardEntity.getExtraJson();
        JSONObject extraJson = new JSONObject();
        if (ObjectUtils.isNotEmpty(extraJsonStr)) {
            extraJson = JSONObject.parseObject(extraJsonStr);
        }
        extraJson.put("receiptContent", receiptContent);
        fansAwardEntity.setExtraJson(extraJson.toJSONString());
        fansAwardEntity.setReceiptState(1);
    }

    /**
     * 核销后奖励积分 TODO 发放积分的方法暂未添加，后续使用需要添加
     **/
    private static void writeOffSendScore(AwardSettingEntity awardSettingEntity) {
        //参与活动积分奖励
        Integer scoreOverType = awardSettingEntity.getScoreOverType();

    }

    /**
     * 更新是否限制可派发人员
     * @param awardId 奖品id
     * @param isAllocationUser 是否限制
     * @param awardType 奖品类型
     */
    public void updateIsAllocationUser(Long awardId, Integer isAllocationUser, Integer awardType) {
        if(null == awardId || null == isAllocationUser || null == awardType){
            throw new BizException("请求参数缺失！");
        }
        AwardSettingEntity awardSetting = baseMapper.selectOne(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, awardId)
                .eq(AwardSettingEntity::getAwardType, awardType));
        if (awardSetting == null) {
            return;
        }
        awardSetting.setIsAllocationUser(isAllocationUser);
        baseMapper.updateById(awardSetting);
    }

    /**
     * 更新是否限制派发机构
     * @param awardId 奖品id
     * @param isAllocation 是否派发
     * @param awardType 奖品类型
     */
    public void updateIsAllocation(Long awardId, Integer isAllocation, Integer awardType) {
        if(null == awardId || null == isAllocation || null == awardType){
            throw new BizException("请求参数缺失！");
        }
        AwardSettingEntity awardSetting = baseMapper.selectOne(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, awardId)
                .eq(AwardSettingEntity::getAwardType, awardType));
        if (awardSetting == null) {
            return;
        }
        awardSetting.setIsAllocation(isAllocation);
        int i = baseMapper.updateById(awardSetting);
        if (i > 0 && isAllocation == 0) {
            //删除机构分配数量表数据
            awardAgentService.remove(AwardAgentEntity.gw()
                    .eq(AwardAgentEntity::getAwardId, awardId)
                    .eq(AwardAgentEntity::getAwardType, awardType));
        }
    }

    /**
     * 奖品配置新增
     * @param awardSettingDTO
     */
    @Transactional
    public Long add(AwardSettingDTO awardSettingDTO) {
        if (ObjectUtils.isEmpty(awardSettingDTO.getAwardId()) || ObjectUtils.isEmpty(awardSettingDTO.getAwardType())) {
            throw new BizException("请选择要新增的奖品");
        }
        AwardSettingEntity awardSettingEntity = new AwardSettingEntity();
        BeanUtils.copyProperties(awardSettingDTO, awardSettingEntity);
        baseMapper.insert(awardSettingEntity);
        if (Constants.AWARD.COUPON == awardSettingDTO.getAwardType()) {
            AwardCouponEntity awardCouponEntity = awardCouponService.getById(awardSettingDTO.getAwardId());
            if (ObjectUtils.isNotEmpty(awardCouponEntity)) {
                awardCouponEntity.setEveryoneMaxNum(awardSettingEntity.getEveryoneMaxNum());
                awardCouponService.updateById(awardCouponEntity);
            }
        }
        return awardSettingEntity.getAwardSettingId();
    }

    /**
     * 卡券配置修改
     * @param awardSettingDTO
     */
    @Transactional
    public void update(AwardSettingDTO awardSettingDTO) {
        if (ObjectUtils.isEmpty(awardSettingDTO.getAwardSettingId())) {
            throw new BizException("请选择要修改的奖品配置");
        }
        AwardSettingEntity awardSettingEntity = baseMapper.selectById(awardSettingDTO.getAwardSettingId());
        if (ObjectUtils.isEmpty(awardSettingEntity)) {
            throw new BizException("所选信息不存在");
        }
        Integer isAllocation = awardSettingEntity.getIsAllocation();
        BeanUtils.copyProperties(awardSettingDTO, awardSettingEntity);
        baseMapper.updateById(awardSettingEntity);
        if (Constants.AWARD.COUPON == awardSettingDTO.getAwardType()) {
            AwardCouponEntity awardCouponEntity = awardCouponService.getById(awardSettingDTO.getAwardId());
            if (ObjectUtils.isNotEmpty(awardCouponEntity)) {
                awardCouponEntity.setEveryoneMaxNum(awardSettingEntity.getEveryoneMaxNum());
                awardCouponService.updateById(awardCouponEntity);
            }
        }

        if (isAllocation != null && isAllocation == 1) {
            String agentNo = null;
            Integer awardNum = null;
            switch (awardSettingDTO.getAwardType()) {
                case Constants.AWARD.COUPON -> {
                    AwardCouponEntity awardCouponEntity = awardCouponService.getById(awardSettingEntity.getAwardId());
                    if (ObjectUtils.isNotEmpty(awardCouponEntity)) {
                        agentNo = awardCouponEntity.getAgentNo();
                        awardNum = awardCouponEntity.getCouponNum();
                    }
                }
                case Constants.AWARD.GOODS -> {
                    AwardGoodsEntity awardGoodsEntity = awardGoodsService.getById(awardSettingEntity.getAwardId());
                    if (ObjectUtils.isNotEmpty(awardGoodsEntity)) {
                        agentNo = awardGoodsEntity.getAgentNo();
                        awardNum = awardGoodsEntity.getGoodsNum();
                    }
                }
                case Constants.AWARD.SCORE -> {
                    AwardScoreEntity awardScoreEntity = awardScoreService.getById(awardSettingEntity.getAwardId());
                    if (ObjectUtils.isNotEmpty(awardScoreEntity)) {
                        agentNo = awardScoreEntity.getAgentNo();
                        awardNum = awardScoreEntity.getScoreNum();
                    }
                }
                case Constants.AWARD.VIRTUAL_COUPON -> {
                    AwardVirtualEntity awardVirtualEntity = awardVirtualService.getById(awardSettingEntity.getAwardId());
                    if (ObjectUtils.isNotEmpty(awardVirtualEntity)) {
                        agentNo = awardVirtualEntity.getAgentNo();
                        awardNum = awardVirtualEntity.getGoodsNum();
                    }
                }
                default -> throw new BizException("奖品类型有误");
            }
            if (ObjectUtils.isNotEmpty(agentNo) && ObjectUtils.isNotEmpty(awardNum)) {
                //更新根机构节点的奖品数量
                AwardAgentEntity rootAwardAgent = awardAgentService.getOne(AwardAgentEntity.gw()
                        .eq(AwardAgentEntity::getAwardId, awardSettingEntity.getAwardId())
                        .eq(AwardAgentEntity::getAwardType, awardSettingDTO.getAwardType())
                        .eq(AwardAgentEntity::getAgentNo, agentNo));
                if (rootAwardAgent != null) {
                    rootAwardAgent.setNum(awardNum);
                    awardAgentService.updateById(rootAwardAgent);
                }
            }
        }
    }

    /**
     * 详情
     * @param awardSettingDTO
     * @return
     */
    public AwardSettingEntity detail(AwardSettingDTO awardSettingDTO) {
        if (ObjectUtils.isEmpty(awardSettingDTO.getAwardSettingId())) {
            throw new BizException("请选择要查询的数据");
        }
        AwardSettingEntity awardSettingEntity = baseMapper.selectById(awardSettingDTO.getAwardSettingId());
        if (ObjectUtils.isEmpty(awardSettingEntity)) {
            throw new BizException("未查询到所选数据");
        }
        return awardSettingEntity;
    }
}
